import http from './http'
import { getCachedData, clearCache } from '@/utils/cache'
import { requestWithRetry } from '@/utils/retry'

// 产品相关API接口定义
export interface Product {
  id: number
  sku: string
  name: string
  specification: string
  unit: string
  categoryId: number | null
  categoryName?: string
  brandId: number | null
  brandName?: string
  description: string
  stock: number
  minStock: number
  salePrice: number
  costPrice: number
  status: string
  createdAt: string
  updatedAt: string
}

// 产品类目接口定义
export interface ProductCategory {
  id: number
  name: string
  parentId: number | null
  level: number
  sort: number
  status: string
  createdAt: string
  updatedAt: string
  children?: ProductCategory[]
}

// 品牌接口定义
export interface Brand {
  id: number
  name: string
  description: string
  status: string
  createdAt: string
  updatedAt: string
}

export interface ProductQueryParams {
  name?: string
  sku?: string
  category?: string
  status?: string
  brand?: string
  specification?: string
  minStock?: number
  page: number
  limit: number
}

export interface ProductListResponse {
  list: Product[]
  pagination: {
    page: number
    limit: number
    total: number
  }
  stats: {
    total: number
    active: number
    lowStock: number
  }
}

// 获取产品列表
export const getProducts = async (params: ProductQueryParams) => {
  try {
    // 使用重试机制获取产品列表
    const response: any = await requestWithRetry(
      () => http.get('/inventory/products', { params }),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    // 确保数值字段被正确转换为数字类型
    const list = (response.data?.list || []).map((product: any) => ({
      ...product,
      stock: Number(product.stock) || 0,
      minStock: Number(product.minStock) || 0,
      salePrice: Number(product.salePrice) || 0,
      costPrice: Number(product.costPrice) || 0
    }));
    
    return {
      success: true,
      data: {
        list,
        pagination: response.data?.pagination || {
          page: 1,
          limit: 20,
          total: 0
        },
        stats: response.data?.stats || {
          total: 0,
          active: 0,
          lowStock: 0
        }
      }
    };
  } catch (error: any) {
    return {
      success: false,
      data: {
        list: [],
        pagination: null,
        stats: {
          total: 0,
          active: 0,
          lowStock: 0
        }
      },
      message: error.message || '获取产品列表失败'
    };
  }
};

// 获取产品统计数据
export const getProductStats = async () => {
  try {
    // 使用缓存机制获取产品统计数据
    const cacheResult: any = await getCachedData(
      'productStats', 
      async () => {
        const response = await http.get('/inventory/products/stats');
        return response.data; // 返回实际的数据而不是整个响应对象
      },
      5 * 60 * 1000 // 5分钟缓存
    );
    
    if (cacheResult.success && cacheResult.data) {
      // 确保数值字段被正确转换为数字类型
      const statsData = {
        ...cacheResult.data,
        totalProducts: Number(cacheResult.data.totalProducts) || 0,
        activeProducts: Number(cacheResult.data.activeProducts) || 0,
        lowStockProducts: Number(cacheResult.data.lowStockProducts) || 0,
        newProducts: Number(cacheResult.data.newProducts) || 0,
        productTrend: Number(cacheResult.data.productTrend) || 0,
        activeTrend: Number(cacheResult.data.activeTrend) || 0,
        lowStockTrend: Number(cacheResult.data.lowStockTrend) || 0,
        newProductTrend: Number(cacheResult.data.newProductTrend) || 0
      };
      return {
        success: true,
        data: statsData
      };
    } else {
      return {
        success: false,
        data: {
          totalProducts: 0,
          activeProducts: 0,
          lowStockProducts: 0,
          newProducts: 0,
          productTrend: 0,
          activeTrend: 0,
          lowStockTrend: 0,
          newProductTrend: 0
        },
        message: cacheResult.message || '获取产品统计数据失败'
      };
    }
  } catch (error: any) {
    return {
      success: false,
      data: {
        totalProducts: 0,
        activeProducts: 0,
        lowStockProducts: 0,
        newProducts: 0,
        productTrend: 0,
        activeTrend: 0,
        lowStockTrend: 0,
        newProductTrend: 0
      },
      message: error.message || '获取产品统计数据失败'
    };
  }
};

// 创建产品
export const createProduct = async (data: Omit<Product, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const result = await http.post('/inventory/products', data);
    // 清除产品相关缓存
    clearCache('products');
    clearCache('productStats');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建产品失败'
    };
  }
};

// 更新产品
export const updateProduct = async (id: number, data: Partial<Product>) => {
  try {
    const result = await http.put(`/inventory/products/${id}`, data);
    // 清除产品相关缓存
    clearCache('products');
    clearCache('productStats');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新产品失败'
    };
  }
};

// 删除产品
export const deleteProduct = async (id: number) => {
  try {
    const result = await http.delete(`/inventory/products/${id}`);
    // 清除产品相关缓存
    clearCache('products');
    clearCache('productStats');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除产品失败'
    };
  }
};

// 复制产品
export const cloneProduct = async (id: number) => {
  try {
    const result = await http.post(`/inventory/products/${id}/clone`);
    // 清除产品相关缓存
    clearCache('products');
    clearCache('productStats');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '复制产品失败'
    };
  }
};

// 批量删除产品
export const batchDeleteProducts = async (ids: number[]) => {
  try {
    const result = await http.post('/inventory/products/batch-delete', { ids });
    // 清除产品相关缓存
    clearCache('products');
    clearCache('productStats');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '批量删除产品失败'
    };
  }
};

// 获取产品详情
export const getProductDetail = async (id: number) => {
  try {
    // 使用重试机制获取产品详情
    const response = await requestWithRetry(
      () => http.get(`/inventory/products/${id}`),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取产品详情失败'
    };
  }
};

// 产品类目相关API

// 获取产品类目树
let categoryTreeCache: ProductCategory[] | null = null;
let categoryTreeTimestamp: number = 0;
const CACHE_TIMEOUT = 5 * 60 * 1000; // 5分钟缓存时间

export const getProductCategories = async () => {
  try {
    // 检查缓存是否有效
    const now = Date.now();
    if (categoryTreeCache && (now - categoryTreeTimestamp) < CACHE_TIMEOUT) {
      return {
        success: true,
        data: categoryTreeCache
      };
    }
    
    // 使用重试机制获取产品类目树
    const response = await requestWithRetry(
      () => http.get('/inventory/categories/tree'),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    // 更新缓存
    categoryTreeCache = response.data;
    categoryTreeTimestamp = now;
    
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取产品类目失败'
    };
  }
};

// 创建产品类目
export const createProductCategory = async (data: Omit<ProductCategory, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const result = await http.post('/inventory/categories', data);
    // 清除类目缓存
    categoryTreeCache = null;
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建产品类目失败'
    };
  }
};

// 更新产品类目
export const updateProductCategory = async (id: number, data: Partial<ProductCategory>) => {
  try {
    const result = await http.put(`/inventory/categories/${id}`, data);
    // 清除类目缓存
    categoryTreeCache = null;
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新产品类目失败'
    };
  }
};

// 删除产品类目
export const deleteProductCategory = async (id: number) => {
  try {
    const result = await http.delete(`/inventory/categories/${id}`);
    // 清除类目缓存
    categoryTreeCache = null;
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除产品类目失败'
    };
  }
};

// 品牌相关API

// 获取品牌列表
export const getBrands = async () => {
  try {
    // 使用缓存机制获取品牌列表
    const result = await getCachedData(
      'brands', 
      () => http.get('/inventory/brands'),
      5 * 60 * 1000 // 5分钟缓存
    );
    
    if (result.success) {
      return {
        success: true,
        data: result.data || []
      };
    } else {
      return {
        success: false,
        data: [],
        message: result.message || '获取品牌列表失败'
      };
    }
  } catch (error: any) {
    return {
      success: false,
      data: [],
      message: error.message || '获取品牌列表失败'
    };
  }
};

// 创建品牌
export const createBrand = async (data: Omit<Brand, 'id' | 'createdAt' | 'updatedAt'>) => {
  try {
    const result = await http.post('/inventory/brands', data);
    // 清除品牌缓存
    clearCache('brands');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '创建品牌失败'
    };
  }
};

// 更新品牌
export const updateBrand = async (id: number, data: Partial<Brand>) => {
  try {
    const result = await http.put(`/inventory/brands/${id}`, data);
    // 清除品牌缓存
    clearCache('brands');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '更新品牌失败'
    };
  }
};

// 删除品牌
export const deleteBrand = async (id: number) => {
  try {
    const result = await http.delete(`/inventory/brands/${id}`);
    // 清除品牌缓存
    clearCache('brands');
    return {
      success: true,
      data: result
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '删除品牌失败'
    };
  }
}

// 导出产品
export const exportProducts = async (params: any) => {
  try {
    const response = await http.get('/inventory/products/export', {
      params,
      responseType: 'blob'
    });
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导出产品失败'
    };
  }
};

// 导入产品
export const importProducts = async (formData: FormData) => {
  try {
    const response = await http.post('/inventory/products/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '导入产品失败'
    };
  }
};

// 获取库存统计数据
export const getInventoryStats = async () => {
  try {
    // 使用重试机制获取库存统计数据
    const response = await requestWithRetry(
      () => http.get('/inventory/stats'),
      3, // 最多重试3次
      1000 // 基础延迟1秒
    );
    
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取库存统计数据失败'
    };
  }
};

// 库存调整接口定义
export interface InventoryAdjustment {
  id: number;
  productId: number;
  sku: string;
  productName: string;
  beforeStock: number;
  afterStock: number;
  adjustQuantity: number;
  adjustType: 'increase' | 'decrease' | 'set';
  reason: string;
  remark: string;
  operatorId: number;
  operatorName: string;
  createdAt: string;
  updatedAt: string;
}

export interface AdjustInventoryParams {
  productId: number;
  adjustType: 'increase' | 'decrease' | 'set';
  adjustAmount: number;
  reason: string;
  remark?: string;
}

// 库存调整
export const adjustInventory = async (params: AdjustInventoryParams) => {
  try {
    const response = await http.post('/inventory/adjustments', params);
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '库存调整失败'
    };
  }
};

// 获取库存调整记录
export interface GetAdjustmentsParams {
  productId?: number;
  page: number;
  limit: number;
}

export const getInventoryAdjustments = async (params: GetAdjustmentsParams) => {
  try {
    const response = await http.get('/inventory/adjustments', { params });
    return {
      success: true,
      data: response.data
    };
  } catch (error: any) {
    return {
      success: false,
      data: null,
      message: error.message || '获取库存调整记录失败'
    };
  }
};
